#include "cspeexencoder.h"

CSpeexEncoder::CSpeexEncoder()
{
    m_nFrameSize = 160;
    m_nFilterLen = 3200;
    m_nSampleRate= 8000;

    m_enc_state = NULL;
    m_pState = NULL;
    m_pPreprocessorState = NULL;
}

CSpeexEncoder::~CSpeexEncoder()
{

}

int CSpeexEncoder::InitSpeex()
{
    m_pState = speex_echo_state_init(m_nFrameSize, m_nFilterLen);
    m_pPreprocessorState = speex_preprocess_state_init(m_nFrameSize, m_nSampleRate);
    int sampleRate = m_nSampleRate;
    speex_echo_ctl(m_pState, SPEEX_ECHO_SET_SAMPLING_RATE, &sampleRate);
    speex_preprocess_ctl(m_pPreprocessorState, SPEEX_PREPROCESS_SET_ECHO_STATE, m_pState);
    int vad = 1;
    speex_preprocess_ctl(m_pPreprocessorState, SPEEX_PREPROCESS_SET_VAD, &vad);

    speex_bits_init(&m_ebits);
    m_enc_state = speex_encoder_init(&speex_nb_mode);
    int tmp = 8;
    speex_encoder_ctl(m_enc_state, SPEEX_SET_QUALITY, &tmp);


    return 0;
}

int CSpeexEncoder::UninitSpeex()
{
    if (m_pState != NULL)
    {
       speex_echo_state_destroy(m_pState);
       m_pState = NULL;
    }
    if (m_pPreprocessorState != NULL)
    {
       speex_preprocess_state_destroy(m_pPreprocessorState);
       m_pPreprocessorState = NULL;
    }

    if(m_enc_state != NULL)
    {
        speex_encoder_destroy(m_enc_state);
         speex_bits_destroy(&m_ebits);
    }

    return 0;
}

int CSpeexEncoder::Encode(short *record, short *play, char *out)
{
    int nbBytes = 0;
    if(play != NULL)
    {
       speex_echo_cancellation(m_pState, record, play, m_processed);
       speex_preprocess_run(m_pPreprocessorState, m_processed);

       speex_bits_reset(&m_ebits);
       speex_encode_int(m_enc_state, m_processed, &m_ebits);
       nbBytes = speex_bits_write(&m_ebits, out, 128);
    }
    else
    {
        speex_preprocess_run(m_pPreprocessorState, record);
        speex_bits_reset(&m_ebits);
        speex_encode_int(m_enc_state, record, &m_ebits);
        nbBytes = speex_bits_write(&m_ebits, out, 128);
    }

    return nbBytes;
}
